'use strict';
var express = require('express');
const short_url = require('../models/short_url');
const _app = require('../models/app')
var router = express.Router();

router.use(async function (req, res, next) {
    if (!req.query["appid"] || !req.query["key"]) {
        res.json({
            status: 0,
            info:"操作错误"
        })
        return
    }
    if (!await _app.check_appid(req.query["appid"], req.query["key"])) {
        res.json({
            status: 0,
            info: "找不到appid"
        })
        return
    }
    req.user = {
        appid: req.query["appid"],
        key: req.query["key"]
    }
    next()
})

router.get("/list", async function (req, res) {
    var page = req.query["page"] || 1
    var pagesize = req.query["page_size"] || 20
    var kw = req.query["kw"] || ""

    var listinfo = await short_url.list_short_url(req.user.appid,kw, page, pagesize)
    res.json({
        status: 1,
        data: listinfo[0],
        count: listinfo[1],
        max_page:Math.ceil(listinfo[1]/pagesize)
    })
})

/* GET users listing. */
router.post('/add', async function (req, res) {
    var appid = req.query["appid"]
    var url = req.body["url"]
    //传时间戳（毫秒级别）
    var exptime = req.body["time"]
    if (!url) {
        res.json({
            status: 0,
            info:"没有链接URL"
        })
        return
    }
    var urllist = url.split(',')
    var key_list=[]
    for (var i = 0; i < urllist.length; i++) {
        var short_key = await short_url.add_short_url(appid, urllist[i], exptime)
        key_list.push(short_key)
    }
    res.json({
        status: 1,
        short_key: key_list,
        info:"success"
    })
});


router.post("/disable", async function (req, res) {
    var k = req.query['k']
    var result = await short_url.disable_short_url(k)
    if (result.modifiedCount >= 1) {
        res.json({
            status: 1,
            num: result.modifiedCount,
            info: "更新成功"
        })
    } else {
        res.json({
            status: 0,
            info:"更新错误"
        })
    }
})



module.exports = router;
